package org.jeecg.modules.demo.crm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.unfbx.chatgpt.exception.BaseException;
import javafx.scene.paint.Material;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.checkerframework.checker.units.qual.A;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.demo.crm.dto.AuditParamDTO;
import org.jeecg.modules.demo.crm.dto.AuditParametersDTO;
import org.jeecg.modules.demo.crm.dto.CProjectApplicationDTO;
import org.jeecg.modules.demo.crm.dto.CSubProjectDTO;
import org.jeecg.modules.demo.crm.entity.*;
import org.jeecg.modules.demo.crm.mapper.*;
import org.jeecg.modules.demo.crm.service.*;
import org.jeecg.modules.demo.crm.util.DateUtils;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

/**
 * @Description: 子项目信息表
 * @Author: jeecg-boot
 * @Date:   2025-05-27
 * @Version: V1.0
 */
@Service
public class CSubProjectServiceImpl extends ServiceImpl<CSubProjectMapper, CSubProject> implements ICSubProjectService {

    @Autowired
    private CProjectApplicationMapper cProjectApplicationMapper;

    @Autowired
    private CSubProjectMapper cSubProjectMapper;

    @Autowired
    private CSubProjectTaskMapper cSubProjectTaskMapper;

    @Autowired
    private CMaterialMapper cMaterialMapper;

    @Autowired
    private CMaterialInfoMapper cMaterialInfoMapper;
    //c_sub_project_status_log
    @Autowired
    private CSubProjectStatusLogMapper cSubProjectStatusLogMapper;

    @Autowired
    private ICSubProjectStatusLogService cSubProjectStatusLogService;

    @Autowired
    private CProjectApplicationMapper projectApplicationMapper;

    @Autowired
    private ICProjectStatusLogService projectStatusLogService;
    @Autowired
    private CContractorInfoMapper contractorInfoMapper;
    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private CProjectQuoteMapper projectQuoteMapper;

    @Autowired
    private CAdditionalRequestMapper cAdditionalRequestMapper;

    @Autowired
    private ICCommonService commonService;


    @Transactional
    @Override
    public void submitReview(AuditParametersDTO auditParametersDTO) {
        CSubProject cSubProject = cSubProjectMapper.selectById(auditParametersDTO.getSubProjectId());
        if(cSubProject==null){
            return;
        }
        //判断状态--只有待报价才能提交
        if( !"报价中".equals(cSubProject.getStatus()) ){
            return;
        }
        String projectId = cSubProject.getProjectId();

        //记录任务
        cSubProjectTaskMapper.deleteBySubProjectId(auditParametersDTO.getSubProjectId());
        auditParametersDTO.getSubmitReviewDTOList().forEach(subReviewDTO -> {

            CSubProjectTask cSubProjectTask = new CSubProjectTask();
            cSubProjectTask.setProjectId(projectId);
            cSubProjectTask.setSubProjectId(cSubProject.getId());
            cSubProjectTask.setTaskName(subReviewDTO.getTaskName());
            cSubProjectTask.setQuantity(subReviewDTO.getQuantity());
            cSubProjectTask.setUnit(subReviewDTO.getUnit());
            cSubProjectTask.setMainPrice(subReviewDTO.getMainPrice());
            cSubProjectTask.setAuxiliaryPrice(subReviewDTO.getAuxiliaryPrice());
            cSubProjectTask.setLaborPrice(subReviewDTO.getLaborPrice());
            cSubProjectTask.setTotalContractor(subReviewDTO.getTotalContractor());
            cSubProjectTask.setRemark(subReviewDTO.getRemark());
            cSubProjectTask.setStatus("审核中");
            cSubProjectTask.setDelFlag(0);
            cSubProjectTaskMapper.insert(cSubProjectTask);
        });
        cSubProject.setStatus("审核中");
        cSubProjectStatusLogService.updateStatus(cSubProject.getId(),cSubProject.getStatus());
        cSubProjectMapper.updateById(cSubProject);
    }

    @Override
    public void assignment(CSubProject cSubProject) {
        String projectId = cSubProject.getProjectId();
        CProjectApplication cProjectApplication = projectApplicationMapper.selectById(projectId);
        if(cProjectApplication != null){
            if("立项".equals(cProjectApplication.getProjectStatus())){
                cProjectApplication.setProjectStatus("报价中");
                projectStatusLogService.updateStatus(cProjectApplication.getId(),cProjectApplication.getProjectStatus());
                cProjectApplicationMapper.updateById(cProjectApplication);
            }
            String contactId = cSubProject.getContactId();
            //指派分包商
            cSubProject.setStatus("报价中");
            CContractorInfo cContractorInfo = contractorInfoMapper.selectById(contactId);
            if(cContractorInfo == null){
                throw new BaseException("分包商所属权限用户不存在");
            }
            String additionalId = cSubProject.getAdditionalId();
            if(additionalId != null && additionalId.length()>0){ //如果增项id不为空
                //解除旧的绑定
                cSubProjectMapper.unbindingAdditionalId(additionalId);
            }
            cSubProject.setUserId(cContractorInfo.getUserId());
            cSubProjectMapper.insert(cSubProject);
            cSubProjectStatusLogService.updateStatus(cSubProject.getId(),cSubProject.getStatus());

            if(additionalId != null && additionalId.length()>0){ //如果增项id不为空
                CAdditionalRequest additionalRequest = cAdditionalRequestMapper.selectById(additionalId);

                additionalRequest.setSubProjectId(cSubProject.getId());
                additionalRequest.setStatus("成立");
                cAdditionalRequestMapper.updateById(additionalRequest);
                //查找如果是 项目需求生成的，把报价记录拉过来
                if(cContractorInfo.getUserId() != null && cContractorInfo.getUserId().length()>0){
                    //用户存在
                    List<CProjectQuote> cProjectQuotes = projectQuoteMapper.quoteRecordByUserIdList(cContractorInfo.getUserId(), additionalId);
                   if(cProjectQuotes != null && cProjectQuotes.size()>0){
                       for (CProjectQuote cProjectQuote : cProjectQuotes) {
                           cProjectQuote.setProjectId(cProjectApplication.getId());
                           cProjectQuote.setSubProjectId(cSubProject.getId());
                           projectQuoteMapper.updateById(cProjectQuote);
                       }
                       cSubProject.setStatus("审核中");
                       cSubProjectStatusLogService.updateStatus(cSubProject.getId(),cSubProject.getStatus());
                       cSubProjectMapper.updateById(cSubProject);
                       cSubProject.setStatus("报价完成");
                       cSubProjectStatusLogService.updateStatus(cSubProject.getId(),cSubProject.getStatus());
                       cSubProjectMapper.updateById(cSubProject);
                   }

                }
            }

        }

    }

    @Override
    public void deleteSubProject(String id) {
       /* CSubProject cSubProject = cSubProjectMapper.selectById(id);
        cSubProject.setDelFlag(1);
        cSubProjectMapper.updateById(cSubProject);*/
        CSubProject cSubProject = cSubProjectMapper.selectById(id);

        //删除合同
        cSubProjectMapper.deleletContract(id);
        //删除报价
        cSubProjectMapper.deleteProjectQuote(id);
        //付款记录
        cSubProjectMapper.deletePaymentRequest(id);
        //收票记录
        cSubProjectMapper.deletePaymentInvoice(id);
        //删除子项目
        cSubProjectMapper.deleteById(id);

    }

    @Override
    public void audit(AuditParamDTO auditParamDTO) {
        CSubProject cSubProject = cSubProjectMapper.selectById(auditParamDTO.getSubProjectId());
        if("完成".equals(auditParamDTO.getStatus())){
            LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            if(!"维保中".equals(cSubProject.getStatus())){
                throw new BaseException("项目状态异常");
            }
            if(sysUser.getRoleCode().contains("admin") || sysUser.getRoleCode().contains("项目经理") || 1==1){
                cSubProject.setStatus("完成");
                cSubProjectStatusLogService.updateStatus(cSubProject.getId(),cSubProject.getStatus(),auditParamDTO.getRemark());
                cSubProjectMapper.updateById(cSubProject);
            }else {
                throw new BaseException("权限不足");
            }
        }else if("维保中".equals(auditParamDTO.getStatus())){
            LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            if(!"施工中".equals(cSubProject.getStatus())){
                throw new BaseException("项目状态异常");
            }
            if(sysUser.getRoleCode().contains("admin") || sysUser.getRoleCode().contains("项目经理") || 1==1){
                cSubProject.setStatus("维保中");
                cSubProjectStatusLogService.updateStatus(cSubProject.getId(),cSubProject.getStatus(),auditParamDTO.getRemark());
                cSubProjectMapper.updateById(cSubProject);
            }else {
                throw new BaseException("权限不足");
            }
        }else {
            if(!"审核中".equals(cSubProject.getStatus())){
                throw new BaseException("项目状态异常");
            }
            LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            if(sysUser.getRoleCode().contains("admin") || sysUser.getRoleCode().contains("项目经理") || 1==1){
                if("同意".equals(auditParamDTO.getStatus())){
                    //
                    CProjectApplication cProjectApplication = cProjectApplicationMapper.selectById(cSubProject.getProjectId());
                    if("报价中".equals(cProjectApplication.getProjectStatus())){
                        cProjectApplication.setProjectStatus("施工中");
                    }
                    projectStatusLogService.updateStatus(cProjectApplication.getId(),cProjectApplication.getProjectStatus());
                    cProjectApplicationMapper.updateById(cProjectApplication);

                    cSubProject.setStatus("施工中");
                    cSubProjectStatusLogService.updateStatus(cSubProject.getId(),cSubProject.getStatus(),auditParamDTO.getRemark());
                    //施工中
                    cSubProjectTaskMapper.updateStatus(cSubProject.getId(),"施工中");
                }else {
                    //驳回
                    cSubProject.setStatus("报价中");
                    cSubProjectStatusLogService.updateStatus(cSubProject.getId(),cSubProject.getStatus(),auditParamDTO.getRemark());
                    cSubProjectTaskMapper.updateStatus(cSubProject.getId(),"驳回");
                }
                cSubProjectMapper.updateById(cSubProject);

            }else {
                throw new BaseException("权限不足");
            }
        }
    }

    @Override
    public void saveContractorId(CSubProject cSubProject) {
        CSubProject cSubProject1 = cSubProjectMapper.selectById(cSubProject.getId());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if(sysUser.getId().equals(cSubProject1.getUserId()) || sysUser.getRoleCode().contains("admin") || 1==1){
            cSubProject1.setContactId(cSubProject.getContactId());
            cSubProjectMapper.updateById(cSubProject1);
        }else {
            throw new BaseException("权限不足");
        }


    }

    @Override
    public CSubProjectDTO getOrderInfo(String id, String subProjectId,  CSubProject subProject) {
        CProjectApplication projectApplication = cProjectApplicationMapper.selectById(id);
        if(projectApplication == null){
            throw new JeecgBootException("总项目不存在");
        }

        CSubProjectDTO subProjectDTO = new CSubProjectDTO();
        subProjectDTO.setProjectName(projectApplication.getProjectName());
        subProjectDTO.setProjectId(projectApplication.getId());
        subProjectDTO.setProjectNumber(projectApplication.getProjectNumber());

        SysUser sysUser2 = userMapper.selectById(subProject.getUserId());
        if(sysUser2 != null){
            subProject.setUserName(sysUser2.getUsername());
        }

        //子项目
        subProjectDTO.setCSubProject(subProject);

        //分包商
        CContractorInfo cContractorInfo = contractorInfoMapper.selectById(subProject.getContactId());
        if(cContractorInfo == null){
            throw new JeecgBootException("分包商不存在");
        }
        SysUser sysUser1 = userMapper.selectById(cContractorInfo.getUserId());
        if(sysUser1 == null){
            // throw new JeecgBootException("权限用户不存在");
        }
        if(sysUser1 != null){
            cContractorInfo.setUserId(sysUser1.getId());
            cContractorInfo.setUserName(sysUser1.getUsername());
        }



        subProjectDTO.setCContractorInfo(cContractorInfo);


        //查询状态
        List<CSubProjectStatusLog> subProjectLog = cSubProjectStatusLogMapper.findSubProjectLog(subProjectId);
        subProjectDTO.setSubProjectStatusLogs(subProjectLog);

        //报价申请
        CProjectQuote quot = projectQuoteMapper.quot(subProject.getId());
        subProjectDTO.setQuot(quot);

        return subProjectDTO;

    }

    @Override
    public void edit(CSubProject cSubProject) {
        CSubProject cSubProject1 = cSubProjectMapper.selectById(cSubProject.getId());
        CContractorInfo cContractorInfo = contractorInfoMapper.selectById(cSubProject.getContactId());
        if(cContractorInfo == null){
            throw new BaseException("分包商所属权限用户不存在");
        }
        //解除旧的 子项目绑定需求
        cAdditionalRequestMapper.unbindingSubProjectId(cSubProject1.getId());

        if(StringUtils.isNotEmpty(cSubProject.getAdditionalId())){
            //如果需求id不为空绑定
            CAdditionalRequest cAdditionalRequest = cAdditionalRequestMapper.selectById(cSubProject.getAdditionalId());
            //需求 解除旧的绑定
            cSubProjectMapper.unbindingAdditionalId(cAdditionalRequest.getId());
            cAdditionalRequest.setStatus("成立");
            cAdditionalRequest.setSubProjectId(cSubProject.getId());
            cAdditionalRequestMapper.updateById(cAdditionalRequest);
        }
        cSubProject.setUserId(cContractorInfo.getUserId());
        cSubProjectMapper.updateById(cSubProject);

    }

    @Override
    public void updateStatus(CSubProject cSubProject) {
        CSubProject cSubProject1 = cSubProjectMapper.selectById(cSubProject.getId());
        if("开始施工".equals(cSubProject.getStatus()) && "报价完成".equals(cSubProject1.getStatus())){
            cSubProject1.setStatus("施工中");
            cSubProject1.setStartDate(new Date());
            cSubProjectStatusLogService.updateStatus(cSubProject1.getId(),cSubProject1.getStatus());
            cSubProjectMapper.updateById(cSubProject1);
        }else if("重新报价".equals(cSubProject.getStatus()) && "报价完成".equals(cSubProject1.getStatus())){
            cSubProject1.setStatus("报价中");
            cSubProjectStatusLogService.updateStatus(cSubProject1.getId(),cSubProject1.getStatus());
            cSubProjectMapper.updateById(cSubProject1);

        }else if("关闭".equals(cSubProject.getStatus()) ) {
            cSubProject1.setStatus("关闭");
            cSubProjectStatusLogService.updateStatus(cSubProject1.getId(),cSubProject1.getStatus());
            cSubProjectMapper.updateById(cSubProject1);
        }else if("完成".equals(cSubProject.getStatus()) && "施工中".equals(cSubProject1.getStatus())){
            cSubProject1.setStatus("完成");
            cSubProject1.setEndDate(new Date());
            cSubProjectStatusLogService.updateStatus(cSubProject1.getId(),cSubProject1.getStatus());
            cSubProjectMapper.updateById(cSubProject1);

        }


    }

    @Override
    public void deleteBatch(List<String> list) {

        for (String id : list) {
            //删除合同
            cSubProjectMapper.deleletContract(id);
            //删除报价
            cSubProjectMapper.deleteProjectQuote(id);
            //付款记录
            cSubProjectMapper.deletePaymentRequest(id);
            //收票记录
            cSubProjectMapper.deletePaymentInvoice(id);
            //删除子项目
            cSubProjectMapper.deleteById(id);
        }

    }

    @Override
    public Map<String, Long> statusCount(CSubProject cSubProject, HttpServletRequest req) {
        CSubProject query = new CSubProject();
        //全部
        Map<String, Long> data = new HashMap<>();
        List<String> statusList = new ArrayList<>();
        statusList.add("全部");
        statusList.add("报价中");
        statusList.add("审核中");
        statusList.add("报价完成");
        statusList.add("驳回");
        statusList.add("施工中");
        statusList.add("施工完成");
        statusList.add("待验收");
        statusList.add("验收完成");
        statusList.add("完成");

        QueryWrapper<CSubProject> queryWrapper = null;
        for (String status : statusList) {
            queryWrapper = QueryGenerator.initQueryWrapper(query, req.getParameterMap());
            if(!status.equals("全部")){
                queryWrapper.eq("status", status);
            }
            if(cSubProject != null && cSubProject.getProjectId() != null){
                queryWrapper.eq("project_id",cSubProject.getProjectId());
            }
            queryWrapper = commonService.permissionDetection(queryWrapper);
            data.put(status,cSubProjectMapper.selectCount(queryWrapper));
        }
        return data;
    }
}
